package com.ziyun.erp.modules.production.operate;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cloud.bus.core.EventBusPusher;
import com.cloud.bus.event.order.OrderMessageEvent;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.logistics.LogisticsSendTypeEnum;
import com.ziyun.erp.common.e.order.OrderItemStatusEnum;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.modules.logistics.dto.ErpLogisticsDto;
import com.ziyun.erp.modules.logistics.entity.ErpLogisticsEntity;
import com.ziyun.erp.modules.logistics.entity.ErpLogisticsItemEntity;
import com.ziyun.erp.modules.logistics.service.ErpLogisticsItemService;
import com.ziyun.erp.modules.logistics.service.ErpLogisticsService;
import com.ziyun.erp.modules.order.entity.ErpOrderLogEntity;
import com.ziyun.erp.modules.order.entity.OrderInfoEntity;
import com.ziyun.erp.modules.order.service.ErpOrderLogService;
import com.ziyun.erp.modules.order.service.OrderInfoService;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.entity.AllotStateEntity;
import com.ziyun.erp.modules.production.operate.entity.AuditStateEntity;
import com.ziyun.erp.modules.production.operate.entity.LogisticsStateEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author guizhao
 * @Title: 生产中状态
 * @ProjectName ziyun-service-erp
 * @date 2018-09-08 15:57
 */
public class ProducingState implements ErpOrderState {

    private static Logger logger = LoggerFactory.getLogger(ProducingState.class);

    private OrderInfoService orderInfoService = SpringContextUtils.getBean("orderInfoService", OrderInfoService.class);
    private ErpLogisticsService erpLogisticsService = SpringContextUtils.getBean("erpLogisticsService", ErpLogisticsService.class);
    private ErpLogisticsItemService erpLogisticsItemService = SpringContextUtils.getBean("erpLogisticsItemService", ErpLogisticsItemService.class);
    private ErpOrderProductionService erpOrderProductionService = SpringContextUtils.getBean("erpOrderProductionService", ErpOrderProductionService.class);
    private ErpOrderItemService erpOrderItemService = SpringContextUtils.getBean("erpOrderItemService", ErpOrderItemService.class);
    private ErpOrderLogService erpOrderLogService = SpringContextUtils.getBean("erpOrderLogService", ErpOrderLogService.class);

    @Override
    public R audit(AuditStateEntity auditStateEntity) {
        return R.error();
    }

    @Override
    public R allot(AllotStateEntity allotStateEntity) {
        return R.error();
    }

    @Override
    public R receive(Integer productionId) {
        return R.error();
    }

    @Override
    public R addLogistics(LogisticsStateEntity logisticsStateEntity, String userId, String createName) {
        // 阳逻发货
        logger.info("=================order addLogistics start================");
        logger.info("=================order addLogistics params：" + logisticsStateEntity.toString());

        ErpLogisticsDto erpLogisticsDto = logisticsStateEntity.getErpLogisticsDto();
        ErpLogisticsEntity erpLogistics = erpLogisticsDto.getErpLogisticsEntity();
        Long orderId = erpLogistics.getOrderId();
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderId);
        // 添加物流信息
        erpLogistics.setCreateName(createName);
        erpLogistics.setSendTime(new Date());
        erpLogisticsService.insert(erpLogistics);
        List<ErpLogisticsItemEntity> erpLogisticsItemList = erpLogisticsDto.getErpLogisticsItemList();
        int itemListSize = erpLogisticsItemList.size();
        if (itemListSize > 0){
            erpLogisticsItemService.saveBatchByLogisticsId(erpLogisticsItemList, erpLogistics.getLogiId());
        }
        int sendType = erpLogistics.getSendType();
        int logiType = erpLogistics.getLogiType();
        if (sendType == LogisticsSendTypeEnum.ORDER.toInt()){
            if (itemListSize > 0){
                List<Integer> itemIds = erpLogisticsItemList.stream().map(ErpLogisticsItemEntity::getOrderItemId).collect(Collectors.toList());
                // 生产单状态 生产中 =》 生产完成
                Map<String, Object> updateMap = new HashMap<>();
                List<ErpOrderProductionEntity> erpOrderProductionList = erpOrderProductionService.selectList(new EntityWrapper<>(new ErpOrderProductionEntity())
                        .eq("del", DeleteEnum.NOT_DELETE.toInt())
                        .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
                        .in("order_item_id", itemIds)
                );
                if (erpOrderProductionList.size() > 0){
                    List<Integer> proIds = erpOrderProductionList.stream().map(ErpOrderProductionEntity::getProductionId).collect(Collectors.toList());
                    updateMap.put("productionStatus", OrderProductionStatusEnum.FINISH.toInt());
                    erpOrderProductionService.updateBatchByMap(updateMap, proIds);
                }
                // 商品状态 生产中 =》 已发货
                updateMap.put("status", OrderItemStatusEnum.DELIVERED.toInt());
                erpOrderItemService.updateBatchByOrderItemId(updateMap, itemIds);
            }
            // 订单状态 生产中 =》 已发货
            erpOrderProductionService.erpOrderItemAddLogistics(orderInfo, logiType);
        }else {
            // 发票、样品（只做记录，不影响订单发货状态）
        }

        // 发送订单发货事件
        OrderMessageEvent event = new OrderMessageEvent(this, Long.valueOf(orderInfo.getUserId()), orderId.toString(), "delivery");
        EventBusPusher.syncPost(event);

        ErpOrderLogEntity erpOrderLog = new ErpOrderLogEntity();
        erpOrderLog.setOrderNo(orderId.toString());
        erpOrderLog.setCreateBy(userId);
        erpOrderLog.setCreateName(createName);
        erpOrderLog.setLogText("添加物流，logiId：" + erpLogistics.getLogiId());
        erpOrderLogService.insert(erpOrderLog);

        logger.info("=================order addLogistics end==================");
        return R.ok();
    }

    @Override
    public R allotPriceFinish(Integer productionId) {
        return R.error();
    }

    @Override
    public R cancleAllot(Integer productionId) {
        return R.error();
    }

}
